package com.nian.global.service.impl;


import com.nian.global.dao.IDao;
import com.nian.global.utils.BeanUtils;
import com.nian.global.utils.CollectionUtils;
import com.nian.global.utils.ConstantUtils;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 设置抽象类，实现基本的增删改查，避免重复开发
 *
 * 遇到特殊的增删改查可在各自的service中单独实现
 * 
 * Created by nian on 2024/1/4.
 */
public abstract class AbstractService_o<T, K> {


    public abstract IDao iDao();

    
    public int add(List<T> commonList) {

        List<K> kList = BeanUtils.copyAs(commonList, (Class<K>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]);
        try {
            iDao().add(kList);
        } catch (Exception e) {
            e.printStackTrace();
            return ConstantUtils.ERROR;
        }
        return ConstantUtils.SUCCESS;
    }

    public int delete(Long[] ids) {

        try {
            iDao().delete(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return ConstantUtils.ERROR;
        }
        return ConstantUtils.SUCCESS;
    }

    public int deleteAll() {

        try {
            iDao().deleteAll();
        } catch (Exception e) {
            e.printStackTrace();
            return ConstantUtils.ERROR;
        }
        return ConstantUtils.SUCCESS;
    }

    public int update(T common) {

        K k = BeanUtils.copyAs(common, (Class<K>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]);
        try {
            iDao().update(k);
        } catch (Exception e) {
            e.printStackTrace();
            return ConstantUtils.ERROR;
        }
        return ConstantUtils.SUCCESS;
    }

    public List<T> queryByIds(Long[] ids) {

        List<K> kList = iDao().queryByIds(ids);
        if (CollectionUtils.isNullOrEmpty(kList)) {
            return null;
        }
        return BeanUtils.copyAs(kList, (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

    public List<T> query(T common) {

        K k = BeanUtils.copyAs(common, (Class<K>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]);
        List<K> kList = iDao().query(k);
        if (CollectionUtils.isNullOrEmpty(kList)) {
            return null;
        }
        return BeanUtils.copyAs(kList, (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

}
